package com.zhou.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.zhou.dto.LoginDto;
import com.zhou.dto.RegisterDto;
import com.zhou.dto.UpdateUserInfoDto;
import com.zhou.entity.vo.*;
import com.zhou.listener.QuestionsAnswersDataListener;
import com.zhou.listener.UpDataListener;
import com.zhou.service.AnswersService;
import com.zhou.service.QuestionsAnswersService;
import com.zhou.service.QuestionsService;
import com.zhou.service.impl.UserRoleServiceImpl;
import com.zhou.service.impl.UserServiceImpl;
import com.zhou.utils.JwtUtils;
import com.zhou.utils.QuestionsAnswersUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;

import static com.zhou.entity.vo.UserVo.fromUser;


@Slf4j
@Validated
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/common")
@Api(tags = "(学生,教师,管理员)通用相关接口")
public class CommonController {

    private final UserServiceImpl userService;

    private final UserRoleServiceImpl userRoleService;

    @Autowired
    private QuestionsService questionsService;
    @Autowired
    private AnswersService answersService;
    @Autowired
    private QuestionsAnswersService questionsAnswersService;



    @RequestMapping("/error")
    public CommonResult<String> error() {
        return CommonResult.<String>builder()
                .code(233)
                .message("请求错误!")
                .build();
    }

    @ApiOperation("用户注册接口")
    @PostMapping("/register")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "user", value = "系统用户实体", required = true, dataType = "user", paramType = "body")
    })
    public CommonResult<String> Register(@RequestBody @Valid RegisterDto registerDto) {
        return CommonResult.<String>builder()
                .data(userService.register(registerDto))
                .build();
    }

    @ApiOperation("用户名合法查询接口")
    @GetMapping("/check/{username}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "系统用户唯一用户名", required = true, dataType = "string", paramType = "path")
    })
    public CommonResult<Boolean> checkUsername(@PathVariable(value = "username") String username) {
        return CommonResult.<Boolean>builder()
                .data(userService.checkUsername(username))
                .build();
    }

    @PostMapping("/login")
    @ApiOperation("用户登录接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "系统用户唯一用户名", required = true, dataType = "string", paramType = "body"),
            @ApiImplicitParam(name = "password", value = "系统用户密码", required = true, dataType = "string", paramType = "body"),
    })
    public CommonResult<String> login(@RequestBody @Valid LoginDto loginDto) {
        return CommonResult.<String>builder()
                .data(userService.login(loginDto))
                .build();
    }

    @GetMapping("/getMenu")
    @ApiOperation(value = "获取不同用户的权限菜单")
    public CommonResult<String> getMenu(HttpServletRequest request) {

        return CommonResult.<String>builder()
                .data(userRoleService.getMenuInfo(JwtUtils.getUserInfoByToken(request).getRoleId()))
                .build();
    }

    @GetMapping("/checkToken")
    @ApiOperation("验证用户token接口")
    public CommonResult<TokenVo> checkToken(HttpServletRequest request) {
        return CommonResult.<TokenVo>builder()
                .data(JwtUtils.getUserInfoByToken(request))
                .build();
    }

    @GetMapping("/getCurrentUser")
    @ApiOperation("供给普通用户查询个人信息使用")
    public CommonResult<UserVo> getCurrentUser(HttpServletRequest request) {
        return CommonResult.<UserVo>builder()
                .data(fromUser(userService.getUserByUsername(JwtUtils.getUserInfoByToken(request).getUsername())))
                .build();
    }

    @PostMapping("/updateCurrentUser")
    @ApiOperation("供给用户更改个人信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "user", value = "系统用户实体", required = true, dataType = "user", paramType = "body")
    })
    public CommonResult<Object> updateCurrentUser(@RequestBody @Valid UpdateUserInfoDto updateUserInfoDto) {
        userService.updateUserInfo(updateUserInfoDto);
        return CommonResult.builder()
                .build();
    }


    //跳转到用户与手机表上传页面
    @RequestMapping("/toUploadPage")
    public String toUploadPage() {
        return "/upupload";
    }

    @RequestMapping("/getAll")
    @ResponseBody
    public List<QuestionsAnswers> getAllUAndP(){
        return questionsAnswersService.selectUAndP();
    }

    //导出到单个sheet
    @GetMapping("/exportWeb1")
    public void exportToWeb1(HttpServletResponse response) {
        try {
            QuestionsAnswersUtils.exportToWeb(response, "用户手机表", "用户拥有手机情况", QuestionsAnswers.class, questionsAnswersService.selectUAndP());
        } catch (Exception e) {
            log.error("报表导出异常:", e);
        }
    }

    //导出到多个sheet
    @GetMapping("/exportWeb2")
    public void exportToWeb2(HttpServletResponse response) {
        try {
            QuestionsAnswersUtils.allExportToWeb(response, "用户手机表",   //excel表格名称
                    "用户表", "手机表",           //excel表格的sheet名称
                    questionsService.getAll(), answersService.getAllPhones());    //导入sheet的两份数据
        } catch (Exception e) {
            log.error("报表导出异常:", e);
        }
    }

    // easyexcel上传文件,单sheet表导入
    @PostMapping("/uploadone")
    @ResponseBody
    public String uploadOne(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), QuestionsAnswers.class, new QuestionsAnswersDataListener(questionsAnswersService)).sheet().doRead();
        return "上传成功";
    }

    // easyexcel上传文件,多sheet表导入
    @PostMapping("/uploadmany")
    @ResponseBody
    public String uploadMany(MultipartFile file) throws IOException {
        ExcelReader excelReader = EasyExcel.read(file.getInputStream()).build();
        // 读取sheet0
        ReadSheet sheet0 = EasyExcel.readSheet(0).head(Questions.class).registerReadListener(new UpDataListener<Questions>(questionsService)).build();
        // 读取sheet1
        ReadSheet sheet1 = EasyExcel.readSheet(1).head(Answers.class).registerReadListener(new UpDataListener<Answers>(answersService)).build();
        excelReader.read(sheet0, sheet1);
        // 这里千万别忘记关闭，读的时候会创建临时文件，到时磁盘会崩的
        excelReader.finish();
        return "上传成功";
    }

}
